package com.neusoft.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import com.neusoft.core.CommonResult;
import com.neusoft.core.User;
import com.neusoft.service.UserService;
import com.neusoft.feign.VirtualWalletFeignClient;

import java.util.Map;
import java.util.List;

//跨域处理
@RefreshScope
@RestController
@RequestMapping("/UserController")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private VirtualWalletFeignClient virtualWalletFeignClient;

    @RequestMapping("/UserLogin")
    public CommonResult<User> getUserByIdByPass(
            @RequestParam("userId") String userId, @RequestParam("password") String password) throws Exception{
        User param = new User();
        param.setUserId(userId);
        param.setPassword(password);
        User user = userService.getUserByIdByPass(param);
        return new CommonResult(200,"success(10100)",user);
    }

    @RequestMapping("/UserPoints")
    public CommonResult<Integer> getPointById(
            @RequestParam("userId") String userId) throws Exception{
        int point = userService.getPointByUser(userId);
        return new CommonResult(200,"success(10100)",point);
    }

    @GetMapping("/User")
    public CommonResult<Integer> getUserById(@RequestParam String userId) throws
            Exception{
        int result = userService.getUserById(userId);
        return new CommonResult(200,"success(10100)",result);
    }

    @PostMapping("/User")
    public CommonResult<Integer> saveUser(
        @RequestParam("userId") String userId, @RequestParam("password") String password,
        @RequestParam("userName") String userName, @RequestParam("userSex") Integer userSex) throws Exception {
    
        // 1. 创建用户对象
        User param = new User();
        param.setUserId(userId);
        param.setPassword(password);
        param.setUserName(userName);
        param.setUserSex(userSex);
        param.setPoints(0);

        // 2. 保存用户基本信息
        int result = userService.saveUser(param);
    
        // 3. 如果用户创建成功，创建虚拟钱包并关联
        if (result > 0) {
            try {
                // 调用钱包服务创建钱包
                CommonResult<Integer> walletResult = virtualWalletFeignClient.saveVirtualWallet(userId);
            
                if (walletResult != null && walletResult.getCode() == 200 && walletResult.getResult() != null) {
                    // 获取钱包ID (已经是int类型)
                    int walletId = walletResult.getResult();
                
                    // 更新用户的钱包ID (直接传递int类型)
                    userService.updateWalletId(userId, walletId);
                
                    // 记录日志
                    System.out.println("用户注册成功，并创建钱包ID: " + walletId);
                } else {
                    System.err.println("用户创建成功但钱包创建失败: " + 
                        (walletResult != null ? walletResult.getMessage() : "null response"));
                }
            } catch (Exception e) {
                // 即使钱包创建失败，也不影响用户注册
                System.err.println("创建钱包时发生异常: " + e.getMessage());
            }
        }
    
        return new CommonResult<>(200, "success(10100)", result);
    }

    @PostMapping("/UserImg")
    public CommonResult<Integer> updateUserImg(@RequestBody Map<String, String> params) throws Exception{
        String userImg = params.get("userImg");
        String userId = params.get("userId");
        int result = userService.updateUserImg(userImg, userId);
        return new CommonResult<>(200, "success(10100)", result);
    }

    @PostMapping("/updateUserTypeByUserId")
    public void updateUserTypeByUserId(User user) throws Exception {
        userService.updateUserTypeByUserId(user.getUserId(), user.getUserType());
    }

    @GetMapping("/walletId")
    public CommonResult<Integer> getWalletIdByUserId(@RequestParam("userId") String userId) throws Exception {
        // 调用服务层方法获取钱包ID
        Integer walletId = userService.getWalletIdByUserId(userId);
        return new CommonResult<>(200, "success(10100)", walletId);
    }

    // @GetMapping("/admin/users-without-wallet")
    // public List<User> findUsersWithoutWallet() {
    //     return userService.findUsersWithoutWallet();
    // }

    @PostMapping("/admin/create-wallet/{userId}")
    public CommonResult<Integer> createWalletForUser(@PathVariable String userId) {
        CommonResult<Integer> walletResult = virtualWalletFeignClient.saveVirtualWallet(userId);
        if (walletResult != null && walletResult.getCode() == 200 && walletResult.getResult() != null) {
            userService.updateWalletId(userId, walletResult.getResult());
            return new CommonResult<>(200, "钱包创建成功", walletResult.getResult());
        }
        return new CommonResult<>(500, "钱包创建失败", -1);
    }

    @GetMapping("/walletIdByBusiness")
    public CommonResult<Integer> getWalletIdByBusinessId(@RequestParam("businessId") Integer businessId) throws Exception {
        // 1. 根据商家ID获取用户ID
        String userId = userService.getUserIdByBusinessId(businessId);
        if (userId == null || userId.isEmpty()) {
            return new CommonResult<>(404, "未找到对应的用户", null);
        }
        
        // 2. 根据用户ID获取钱包ID
        Integer walletId = userService.getWalletIdByUserId(userId);
        if (walletId == null) {
            return new CommonResult<>(404, "该商家未绑定钱包", null);
        }
        
        return new CommonResult<>(200, "success(10100)", walletId);
    }
}